package ch.ti.bfh.app.loodel.web.utils;

import ch.ti.bfh.app.loodel.service.create.ShowTimeSlotLocationData;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang3.SerializationException;
import org.apache.commons.lang3.SerializationUtils;
import org.springframework.security.crypto.codec.Base64;
import org.springframework.stereotype.Component;

import java.io.Serializable;

@Component("timeSlotLocationDataAutcompleteConverter")
public class TimeSlotLocationDataAutocompleteConverter extends AbstractPrimefacesAutoCompleteConverter<ShowTimeSlotLocationData> {
    @Override
    protected ShowTimeSlotLocationData getAsObjectFromAutocompleteSuggestionValue(String value) {
        if (StringUtils.isNotEmpty(value)) {
            try {
                return (ShowTimeSlotLocationData) SerializationUtils.deserialize(Base64.decode(value.getBytes()));
            } catch (SerializationException e) {
                // Nothing to do
            }
        }
        return null;
    }

    @Override
    public String getAsStringForAutocompleteSuggestionValue(Object value) {
        if (value instanceof ShowTimeSlotLocationData) {
            return new String(Base64.encode(SerializationUtils.serialize((Serializable) value)));
        }
        return null;
    }
}
